﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace MS.Utility.Common
{
    /// <summary>
    /// 验证码功能类
    /// </summary>
    public class ValidateCodeHelper
    {
        #region 数字验证码
        private const double PI = 0;
        private const double PI2 = 0;

        private static string GenerateCheckCode(int number)
        {
            string checkCode = String.Empty;
            string varChar = "1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,m,n,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z";
            string[] vcArray = varChar.Split(',');
            var random = new Random();
            for (int i = 1; i < number + 1; i++)
            {
                int t = random.Next(vcArray.Length);
                checkCode += vcArray[t];
            }
            HttpContext.Current.Session["ValidateCode"] = checkCode;
            return checkCode;
        }

        private static Bitmap TwistImg(Bitmap img, bool isTwist, double nMult, double start)
        {
            var bitmap = new Bitmap(img.Width, img.Height);
            Graphics g = Graphics.FromImage(bitmap);
            g.FillRectangle(new SolidBrush(Color.White), 0, 0, bitmap.Width, bitmap.Height);
            g.Dispose();
            double axisLen = isTwist ? bitmap.Height : bitmap.Width;
            for (int i = 0; i < bitmap.Width; i++)
            {
                for (int j = 0; j < bitmap.Height; j++)
                {
                    double dx = 0;
                    dx = isTwist ? (PI2 * j) / axisLen : (PI2 * i) / axisLen;
                    dx += start;
                    double dy = Math.Sin(dx);
                    int ox = 0;
                    int oy = 0;
                    ox = isTwist ? i + (int)(dy * nMult) : i;
                    oy = isTwist ? j : j + (int)(dy * nMult);
                    Color color = img.GetPixel(i, j);
                    if (ox >= 0 && ox < bitmap.Width && oy >= 0 && oy < bitmap.Height)
                    {
                        bitmap.SetPixel(ox, oy, color);
                    }
                }
            }
            return bitmap;
        }

        public static byte[] CreateCheckCodeImage(int number)
        {
            string checkCode = GenerateCheckCode(number);
            if (checkCode == null || checkCode.Trim() == String.Empty)
            {
                return null;
            }
            var bitmap = new Bitmap(checkCode.Length + 120, 40);
            Graphics g = Graphics.FromImage(bitmap);
            try
            {
                var random = new Random();
                g.Clear(Color.White);
                var font = new Font("Arial", 24, FontStyle.Bold);
                var brush = new LinearGradientBrush(new Rectangle(0, 0, bitmap.Width, bitmap.Height),
                                                    Color.Blue, Color.DarkRed, 1.2f, true);
                g.DrawString(checkCode, font, brush, 2, 2);

                //画图片的前景噪音点
                for (int i = 0; i < 100; i++)
                {
                    int x = random.Next(bitmap.Width);
                    int y = random.Next(bitmap.Height);
                    bitmap.SetPixel(x, y, Color.FromArgb(random.Next()));
                }

                //画图片的边框线
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, bitmap.Width - 1, bitmap.Height - 1);
                Bitmap bt = TwistImg(bitmap, true, 10, 0);
                var memoryStream = new MemoryStream();
                bt.Save(memoryStream, ImageFormat.Gif);
                return memoryStream.ToArray();
            }
            finally
            {
                g.Dispose();
                bitmap.Dispose();
            }
        }
        #endregion

        #region 滑块验证码
        /// <summary>
        /// 生成滑块验证图片
        /// 
        /// </summary>
        /// <param name="offsetX">缺口坐标x的偏移量</param>
        /// <param name="sImgFolderPath">图片文件夹的位置，文件夹中的图片必须以纯数字命名，例如1.png,2.png,...</param>
        /// <param name="imgMarkPath">缺口图片1的路径</param>
        /// <param name="imageMark2Path">缺口图片2的路径</param>
        /// <param name="ext">图片后缀名</param>
        /// <param name="bgNum">随机图片的数量</param>
        /// <param name="bgWidth">背景图片的宽度</param>
        /// <param name="bgHeight">背景图片的高度</param>
        /// <param name="markWidth">缺口图片的宽度</param>
        /// <param name="markHeight">缺口图片的高度</param>
        /// <returns>二进制图像</returns>
        public static byte[] CreateSilderCodeImage(out int offsetX,string sImgFolderPath,string sImgMarkPath,string sImgMark2Path,string sExt="png",int bgNum=6,int bgWidth=240,int bgHeight=150,int markWidth=50,int markHeight=50)
        {
            //定义缺口的x坐标点
            int x = 0;
            //定义缺口的y坐标点
            int y = 0;
            //定义背景图片，从背景图片中随机取一个
            int bg = new Random().Next(1, 6);
            string sImgPath = Path.Combine(sImgFolderPath, bg.ToString()+ "." + sExt);
            //从路径中加载完整的背景图片
            Image imgFullBg = Image.FromFile(sImgPath);
            imgFullBg = pictureProcess(imgFullBg, bgWidth, bgHeight);

            //创建一个纯色的图片
            Image imgBg = new Bitmap(bgWidth, bgHeight);
            Graphics gBg = Graphics.FromImage(imgBg);
            gBg.Clear(Color.Black);
            gBg.DrawImage(imgFullBg, 0, 0, bgWidth, bgHeight);
            x = new Random().Next(50, bgWidth - markWidth - 1);
            offsetX = x;
            y = new Random().Next(0, bgHeight - markHeight - 1);

            //创建滑块图片
            Bitmap imgSilder = new Bitmap(markWidth, bgHeight);
            //从路径中加载缺口图片2，代表滑块
            Image imgMark2 = Image.FromFile(sImgMark2Path);
            imgMark2 = pictureProcess(imgMark2, markWidth, markHeight);

            Graphics gSilder = Graphics.FromImage(imgSilder);
            gSilder.DrawImage(imgFullBg, 0, y, new Rectangle(x,y,markWidth,markHeight), GraphicsUnit.Pixel);
            gSilder.DrawImage(imgMark2, 0, y, new Rectangle(0, 0, markWidth, markHeight), GraphicsUnit.Pixel);
            imgSilder.MakeTransparent(Color.Black);
            //从路径中加载缺口图片
            Image imgMark = Image.FromFile(sImgMarkPath);
            imgMark = pictureProcess(imgMark, markWidth, markHeight);
            Bitmap bmpMark = new Bitmap(imgMark);
            bmpMark.MakeTransparent();
            gBg.DrawImage(bmpMark, x, y, new Rectangle(0, 0, markWidth, markHeight), GraphicsUnit.Pixel);
            

            //创建完整图片
            Bitmap imgFinal = new Bitmap(bgWidth, bgHeight * 3);
            Graphics gFinal = Graphics.FromImage(imgFinal);
            gFinal.Clear(Color.Transparent);
            gFinal.DrawImage(imgBg, 0, 0, new Rectangle(0, 0, bgWidth, bgHeight),GraphicsUnit.Pixel);
            gFinal.DrawImage(imgSilder, 0, bgHeight, new Rectangle(0, 0, markWidth, bgHeight), GraphicsUnit.Pixel);
            gFinal.DrawImage(imgFullBg, 0, bgHeight*2, new Rectangle(0, 0, bgWidth, bgHeight), GraphicsUnit.Pixel);
            imgFinal.MakeTransparent();
            try
            {
                MemoryStream memoryStream = new MemoryStream();
                EncoderParameters encoderparameters = new EncoderParameters(1);
                EncoderParameter encoderparameter = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
                encoderparameters.Param[0] = encoderparameter;

                ImageCodecInfo myImageCodecInfo = GetEncoderInfo("image/png");
                imgFinal.Save(memoryStream, myImageCodecInfo,encoderparameters);
                return memoryStream.ToArray();
            }
            finally
            {
                imgFinal.Dispose();
                imgBg.Dispose();
                imgSilder.Dispose();
                imgFullBg.Dispose();
                imgMark.Dispose();
                imgMark2.Dispose();

                gFinal.Dispose();
                gSilder.Dispose();
                gBg.Dispose();

                bmpMark.Dispose();
                
            }


        }
        /// <summary>
        /// 等比缩放图片
        /// </summary>
        /// <param name="sourceImage"></param>
        /// <param name="targetWidth"></param>
        /// <param name="targetHeight"></param>
        /// <returns></returns>
        private static Image pictureProcess(Image sourceImage, int targetWidth, int targetHeight)
        {
            int width;//图片最终的宽
            int height;//图片最终的高
            try
            {
                System.Drawing.Imaging.ImageFormat format = sourceImage.RawFormat;
                Bitmap targetPicture = new Bitmap(targetWidth, targetHeight);
                Graphics g = Graphics.FromImage(targetPicture);
                g.Clear(Color.Transparent);

                //计算缩放图片的大小
                if (sourceImage.Width > targetWidth && sourceImage.Height <= targetHeight)
                {
                    width = targetWidth;
                    height = (width * sourceImage.Height) / sourceImage.Width;
                }
                else if (sourceImage.Width <= targetWidth && sourceImage.Height > targetHeight)
                {
                    height = targetHeight;
                    width = (height * sourceImage.Width) / sourceImage.Height;
                }
                else if (sourceImage.Width <= targetWidth && sourceImage.Height <= targetHeight)
                {
                    width = sourceImage.Width;
                    height = sourceImage.Height;
                }
                else
                {
                    width = targetWidth;
                    height = (width * sourceImage.Height) / sourceImage.Width;
                    if (height > targetHeight)
                    {
                        height = targetHeight;
                        width = (height * sourceImage.Width) / sourceImage.Height;
                    }
                }
                g.DrawImage(sourceImage, (targetWidth - width) / 2, (targetHeight - height) / 2, width, height);
                sourceImage.Dispose();
               
                return targetPicture;
            }
            catch  
            {
            }
            return null;
        }
 
        /// <summary>
        /// 获取ImageCodecInfo
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        private static ImageCodecInfo GetEncoderInfo(String mimeType)

        {
            int j;
            ImageCodecInfo[] encoders;
            encoders = ImageCodecInfo.GetImageEncoders();
            for (j = 0; j < encoders.Length; ++j)
            {
                if (encoders[j].MimeType == mimeType)
                    return encoders[j];
            }
            return null;
        }
 

        /// <summary>
        /// 滑块验证码校验
        /// </summary>
        /// <param name="userOffsetX">用户移动的坐标</param>
        /// <param name="targetX">目标坐标</param>
        /// <param name="fault">允许偏移量，该值越小越严格</param>
        /// <returns>返回一个int类型的值，1代表通过，0代表不通过。</returns>
        public static int CheckSilderCode(int userOffsetX,int targetX,int fault = 3)
        {
            return Math.Abs(targetX - userOffsetX) <= fault ? 1 : 0;
        }

        #endregion

    }
}
